package cn.mayday.algorithms.year2021.month1.E栈专题;

import java.util.Stack;

/**
 * @description: TODO
 * @author: mayday
 * @date: 2021/1/12 21:31
 * @version: 1.0
 */
public class Offer30MinStack2 {

    public static void main(String[] args) {

    }

    /** initialize your data structure here. */
    public Offer30MinStack2() {

    }

    private Stack<Integer> stackA = new Stack();
    private Stack<Integer> stackB = new Stack();


    public void push(int x) {
        stackA.push(x);
        // 辅助栈，保存当前最小的值
        if (stackB.isEmpty()) {
            stackB.push(x);
        } else {
            // 如果入栈的数值比辅助栈要小，继续入栈
            if (stackB.peek() >= x) {
                stackB.push(x);
            }
        }
    }

    public void pop() {
        // 如果不为空，出栈，如果主栈出栈的元素等于辅助栈的栈顶元素，辅助栈对应也出栈
        // 这样就能保证辅助栈的栈顶永远保存当前最小值
        if (!stackA.isEmpty()) {
            int temp = stackA.pop();
            if (temp == stackB.peek()) {
                stackB.pop();
            }
        }
    }

    public int top() {
        return stackA.peek();
    }

    public int min() {
        if (!stackB.isEmpty()) {
            return stackB.peek();
        }
        return -1;
    }

}
